package com.ruoyi.business.service;

import com.ruoyi.bizsys.domain.LoanIou;
import com.ruoyi.bizsys.domain.ReduceConfig;
import com.ruoyi.bizsys.mapper.ReduceConfigMapper;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.business.Vo.CustReduceRes;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

@Slf4j
@Component
public class DoCalCustReduce {

    @Autowired
    private List<CustReduceProess> custReduceProess;
    @Autowired
    private ILoanIouService loanIouService;
    @Autowired
    ReduceConfigMapper reduceConfigMapper;

    public CustReduceRes checkCustReduce(String loanSerialNo){
        LoanIou loanIou = loanIouService.getLoanIouByLoanSerialNo(loanSerialNo);
        ReduceConfig reduceConfig = reduceConfigMapper.getStatucOn();
        CustReduceRes custReduceRes = initCustReduceRes(loanIou);
        if(null==reduceConfig){
            log.info("reduceConfig未配置");
            custReduceRes.setIsHave(false);
            return custReduceRes;
        }
        Collections.sort(custReduceProess, AnnotationAwareOrderComparator.INSTANCE);
        int size = custReduceProess.size();
        for (int i = 0; i < size; i++) {
            custReduceRes = custReduceProess.get(i).handle(reduceConfig,loanIou,custReduceRes);
            if(!custReduceRes.getIsHave()){
                break;
            }
        }
        custReduceRes.setCurrentAmt(custReduceRes.getOrgAmt().subtract(custReduceRes.getReduceAmont()));
        return custReduceRes;
    }

    /**
     * 初始化CustReduceRes
     * @param loanIou
     * @return
     */
    private CustReduceRes initCustReduceRes(LoanIou loanIou) {
        CustReduceRes custReduceRes = new CustReduceRes();
        custReduceRes.setIsHave(true);
        custReduceRes.setReduceAmont(BigDecimal.ZERO);
        custReduceRes.setOrgAmt(LoanIou.calculationOverdueAmount(loanIou));
        custReduceRes.setCurrentAmt(BigDecimal.ZERO);
        return custReduceRes;
    }
}
